#include "A_Config.h"

static lv_obj_t *obj_weather_48h;
static lv_obj_t *chart;
lv_chart_series_t *ser1;
lv_chart_series_t *ser2;

void tile_weather_48h_update(uint8_t month, uint8_t date, uint8_t hour)
{
    int8_t remaining = 0, now = 0;
    int16_t max_temp = -100, max_rain = -100, min_temp = 32767, min_rain = 32767;
    weatherInfo24H *p = weather.getWeather(month, date, hour);
    for (remaining = 0; remaining < 120; ++remaining)
    {
        if (p == &weather.hour24[remaining])
        {
            now = remaining;
            break;
        }
    }
    remaining = 120 - remaining;
    if (remaining > 48)
        remaining = 48;
    if (remaining != 0)
    {
        for (uint8_t i = now; i < now + remaining; ++i)
        {
            max_temp = max(max_temp, (int16_t)(weather.hour24[i].temperature / 10));
            min_temp = min(min_temp, (int16_t)(weather.hour24[i].temperature / 10));
            max_rain = max(max_rain, (int16_t)(weather.hour24[i].rain));
            min_rain = min(min_rain, (int16_t)(weather.hour24[i].rain));
            ser1->y_points[i - now] = weather.hour24[i].temperature / 10;
            ser2->y_points[i - now] = weather.hour24[i].rain;
        }
    }
    else
    {
        max_temp = 40, max_rain = 200, min_temp = -20, min_rain = 0;
    }
    if (remaining < 48)
    {
        for (uint8_t i = remaining; i < 48; ++i)
        {
            ser1->y_points[i] = 0;
            ser2->y_points[i] = 0;
        }
    }
    lv_chart_set_range(chart, LV_CHART_AXIS_PRIMARY_Y, min_temp, max_temp);
    lv_chart_set_range(chart, LV_CHART_AXIS_SECONDARY_Y, 0, max_rain < 50 ? 50 : max_rain);
    lv_chart_refresh(chart); /*Required after direct set*/
}

void tile_weather_48h_create(lv_obj_t *tile)
{
    obj_weather_48h = lv_obj_create(tile);
    lv_obj_set_style_pad_all(obj_weather_48h, 4, 0);
    lv_obj_set_size(obj_weather_48h, 208, 114);
    lv_obj_set_pos(obj_weather_48h, 4, 122);

    chart = lv_chart_create(obj_weather_48h);
    lv_obj_set_size(chart, lv_pct(68), lv_pct(78));
    lv_obj_set_align(chart, LV_ALIGN_TOP_MID);
    lv_chart_set_type(chart, LV_CHART_TYPE_LINE); /*Show lines and points too*/
    lv_chart_set_point_count(chart, 48);

    /*Add two data series*/
    lv_chart_set_axis_tick(chart, LV_CHART_AXIS_PRIMARY_X, 10, 5, 48, 2, true, 30);
    lv_chart_set_axis_tick(chart, LV_CHART_AXIS_PRIMARY_Y, 10, 5, 3, 2, true, 40);
    lv_chart_set_axis_tick(chart, LV_CHART_AXIS_SECONDARY_Y, 10, 5, 3, 2, true, 40);
    lv_chart_set_range(chart, LV_CHART_AXIS_PRIMARY_Y, -20, 40);
    lv_chart_set_range(chart, LV_CHART_AXIS_SECONDARY_Y, 0, 400);
    ser1 = lv_chart_add_series(chart, lv_palette_main(LV_PALETTE_RED), LV_CHART_AXIS_PRIMARY_Y);
    ser2 = lv_chart_add_series(chart, lv_palette_main(LV_PALETTE_BLUE), LV_CHART_AXIS_SECONDARY_Y);
    lv_chart_set_zoom_x(chart, 2048);
}